﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
using Wozuji.Common;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;



namespace Wozuji.Logic.Users
{
   
    public  class Users
    {
        
       

        
        #region  用户登录
        /// <summary>
        /// 判断用户是否登录，如果用户已经登录，则设置用profile
        /// </summary>
        /// <param name="username">用户名或者Email</param>
        /// <param name="password">用户密码</param>
        /// <param name="autoflag">是否自动登陆标志</param>
        /// <returns></returns>
        public  bool userLogin(string username, string password, bool autoflag)
        {
            try
            {

                Wozuji.Model.Member_t mb = new Wozuji.Model.Member_t();
                Wozuji.BLL.Member_t bmb = new Wozuji.BLL.Member_t();
                mb = bmb.GetModel(username, Wozuji.Common.Util.StringUtil.EncryptPassword(password, Wozuji.Common.Util.StringUtil.PasswordType.MD5.ToString()));
                //登录成功
                if (!(mb == null))
                {
                    setUserProfile(mb, autoflag);
                    mb = null;
                    bmb = null;
                    return true;
                }
                else
                {
                    mb = null;
                    bmb = null;
                    return false;
                }
            }
            catch (Exception ex)
            {
                return false;
            }


        }
        #endregion

        #region 登录成功设置profile
        /// <summary>
        /// 登录成功，设置用户profile
        /// </summary>
        /// <param name="User"></param>
        /// <param name="autoFlag"></param>
        public  void setUserProfile(Wozuji.Model.Member_t User, bool autoFlag)
        {
            //加入用户session

            HttpContext.Current.Session.RemoveAll();
            HttpContext.Current.Session["userid"] = User.Member_Id.ToString();
            HttpContext.Current.Session["username"] = User.Member_FriendName.ToString();
            HttpContext.Current.Session["member_face"] = User.Member_Face.ToString();
            HttpContext.Current.Session["member_friendname"] = User.Member_FriendName.ToString();
            HttpContext.Current.Session["member_logintime"] = User.Member_LoginTime.ToString();
            HttpContext.Current.Session["member_money"] = User.Member_Money.ToString();
            HttpContext.Current.Session["member_name"] = User.Member_Name.ToString();
            HttpContext.Current.Session["member_sex"] = User.Member_Sex.ToString();
            HttpContext.Current.Session["member_sign"] = User.Member_sign.ToString();


            //更新用户信息

            User.member_LoginIp = HttpContext.Current.Request.UserHostAddress.ToString();
            User.Member_Os = HttpContext.Current.Request.Browser.Platform.ToString();
            User.Member_brower = HttpContext.Current.Request.Browser.Version.ToString();
            User.Member_Screensize = HttpContext.Current.Request.Browser.ScreenPixelsWidth.ToString() + "X" + HttpContext.Current.Request.Browser.ScreenPixelsHeight.ToString();

            if (autoFlag)
            {
                Wozuji.Common.randomCode.randomCode rc = new Wozuji.Common.randomCode.randomCode();
                User.Member_AutoLoginSerial = rc.CreateCode(64);
                setAutoLogin(User.Member_Id.ToString(), User.Member_FriendName.ToString(), User.Member_AutoLoginSerial);
            }
            else
            {
                User.Member_AutoLoginSerial = "false";
                setAutoLogin(User.Member_Id.ToString(), User.Member_FriendName.ToString(), "false");
            }
            Wozuji.BLL.Member_t mbBll = new Wozuji.BLL.Member_t();
            mbBll.Update(User);

            User = null;



        }
        #endregion

        #region 记住用户写cookie
        /// <summary>
        /// 记住用户登录
        /// 主要操作为 在用户登录时在用户的cookie中添加一个随机生成验证码，同时将这个验证码写入数据库
        /// 用户id写入cookie，当用户再次访问时，检查验证码是否与用户登录时写入的是否一致
        /// 以免cookie欺诈
        /// 
        /// </summary>
        /// <param name="userid">用户id</param>
        /// <returns>用户id，随机码</returns>
        /// 
        private  void setAutoLogin(string userid, string username, string code)
        {



            Wozuji.Common.Cookie.MyCookie ck = new Wozuji.Common.Cookie.MyCookie();
            Wozuji.Common.Util.StringUtil su = new Wozuji.Common.Util.StringUtil();
            string oldCookie = "";
            try
            {
                oldCookie = ck.GetCookie("userid").Value;
            }
            catch (Exception ex)
            {

            }

            if (oldCookie != "")
            {

                ck.SetCookie("userid", userid, DateTime.Now.AddDays(30));
                ck.SetCookie("serial", code, DateTime.Now.AddDays(30));
                ck.SetCookie("username", su.encodeUnicode(username), DateTime.Now.AddDays(30));
            }
            else
            {
                ck.AddCookie("userid", userid, DateTime.Now.AddDays(30));
                ck.AddCookie("serial", code, DateTime.Now.AddDays(30));
                ck.AddCookie("username", su.encodeUnicode(username), DateTime.Now.AddDays(30));
            }



        }

        /// <summary>
        /// 记住用户登录
        /// 主要操作为 在用户登录时在用户的cookie中添加一个随机生成验证码，同时将这个验证码写入数据库
        /// 用户id写入cookie，当用户再次访问时，检查验证码是否与用户登录时写入的是否一致
        /// 以免cookie欺诈
        /// 
        /// </summary>
        /// <param name="userid">用户id</param>
        /// <returns>用户id，随机码</returns>
        /// 
        private  void setAutoLogin(string userid, string username, bool flag)
        {

            Wozuji.Common.Util.StringUtil su = new Wozuji.Common.Util.StringUtil();


            Wozuji.Common.Cookie.MyCookie ck = new Wozuji.Common.Cookie.MyCookie();
            string oldCookie = "";
            try
            {
                oldCookie = ck.GetCookie("userid").Value;
            }
            catch (Exception ex)
            {

            }

            if (oldCookie != "")
            {

                ck.SetCookie("userid", userid, DateTime.Now.AddDays(30));
                ck.SetCookie("serial", "00000000000000000000000000000", DateTime.Now.AddDays(30));
                ck.SetCookie("username", su.encodeUnicode(username), DateTime.Now.AddDays(30));
            }
            else
            {
                ck.AddCookie("userid", userid, DateTime.Now.AddDays(30));
                ck.AddCookie("serial", "00000000000000000000000000000", DateTime.Now.AddDays(30));
                ck.AddCookie("username", su.encodeUnicode(username), DateTime.Now.AddDays(30));
            }



        }

        public  void delCookie(string userid)
        {
            Wozuji.Common.Cookie.MyCookie ck = new Wozuji.Common.Cookie.MyCookie();

            try
            {
                ck.RemoveCookie("userid");
                ck.RemoveCookie("serial");
            }
            catch (Exception ex) { }
        }

        #endregion

        #region 校验记住用户登录
        public  bool getAutoLogin()
        {

            int oldCookie_username;
            string oldCoolie_Serial = "";
            Wozuji.Common.Cookie.MyCookie ck = new Wozuji.Common.Cookie.MyCookie();
            try
            {
                oldCookie_username = Convert.ToInt32(ck.GetCookie("userid").Value);
                oldCoolie_Serial = ck.GetCookie("serial").Value;
            }
            catch (Exception ex)
            {
                return false;
            }
            //过滤serial=false;
            if ((oldCookie_username.Equals("") || oldCookie_username.Equals("false")) || oldCookie_username.Equals("") || oldCookie_username.Equals(""))
            {
                return false;
            }
            else
            {

                Wozuji.BLL.Member_t bdal = new Wozuji.BLL.Member_t();
                Wozuji.Model.Member_t mb = new Wozuji.Model.Member_t();
                mb = bdal.GetModel_AutoLogin(oldCookie_username, oldCoolie_Serial);

                HttpContext.Current.Session["userid"] = mb.Member_Id.ToString();
                Wozuji.Common.randomCode.randomCode rc = new Wozuji.Common.randomCode.randomCode();
                setAutoLogin(mb.Member_Id.ToString(), mb.Member_FriendName.ToString(), rc.CreateCode(64));
                return true;

            }


        }

        #endregion

        #region 用户是否登录
        /// <summary>
        /// 判断用户是否登录
        /// </summary>
        /// 
        /// <returns>true 为登录，false 为未登录</returns>

        public  bool isLogin()
        {
            string aa = "";
            try
            {
                aa = HttpContext.Current.Session["userid"].ToString();
            }
            catch (Exception ex)
            {
                aa = "";
            }
            if (aa.Equals(""))
            {

                if (getAutoLogin())
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {

                return true;

            }
        }



        #endregion

        #region 恢复用户密码
        public  bool rescoverPassword(string code, string pass)
        {
            try
            {
                pass = Wozuji.Common.Util.StringUtil.EncryptPassword(pass, Wozuji.Common.Util.StringUtil.PasswordType.MD5.ToString());
                Wozuji.BLL.Member_t mbdal = new Wozuji.BLL.Member_t();
                Wozuji.Model.Member_t mb = new Wozuji.Model.Member_t();
                mb = mbdal.getModel_ByCode(code);
                if (!mb.Equals(null))
                {
                    mb.Member_Password = pass;
                    mb.Member_BackPasswordCode = "false";
                    mbdal.Update(mb);
                    return true;
                }
                else
                {
                    return false;
                }

            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion

        #region 用户找回密码
        /// <summary>
        /// 得到用户密码密文取出，发给用户，用户在修改密码时直接验证密码
        /// </summary>
        /// <param name="email">取回密码的邮箱</param>
        /// <returns></returns>
        public  bool getBackPassword(string email)
        {
            //使用当前时间做为验证码的生成字符
            string code = Wozuji.Common.Util.StringUtil.EncryptPassword(DateTime.Now.ToString(), Wozuji.Common.Util.StringUtil.PasswordType.MD5.ToString());
            //将数据写入数据库
            Wozuji.Model.Member_t mb = new Wozuji.Model.Member_t();
            Wozuji.BLL.Member_t mbdal = new Wozuji.BLL.Member_t();
            mb = mbdal.getModel_ByEmail(email);
            mb.Member_BackPasswordCode = code;
            mb.Member_BackPasswordTime = DateTime.Now.AddDays(1);
            mbdal.Update(mb);
            try
            {

                //发送通知邮件
                string content;
                content = "<DIV>&nbsp;</DIV><BR><DIV><IMG src=\"http://wozuji.com/images/logo.png\"></DIV><HR><DIV style=\"PADDING-BOTTOM: 20px; PADDING-LEFT: 20px; PADDING-RIGHT: 20px; FONT-FAMILY: Verdana; PADDING-TOP: 20px; line-heigth: 25px\" class=main><P>尊敬的用户：</P><P>&nbsp;&nbsp;&nbsp;&nbsp;您好！ 非常感谢您使用我足迹网站服务。您的帐号名为 <B style=\"COLOR: #009fe8\">*****</B> ，您申请了密码找回服务，现将您的找回密码的认证码发给您（如果超过1天使用，系统将视为无效找回，本次找回操作取消）。</P><P>　密码找回地址：<A href=\"http://www.wozuji.com/u/passactivate.aspx?code=#####\">http://www.wozuji.com/u/passactivate.aspx?code=#####</A><BR>（如果地址不能点击，请复制地址到浏览器中访问） </P><DIV style=\"BORDER-BOTTOM: #ccc 2px solid; BORDER-LEFT: #ccc 2px solid; PADDING-BOTTOM: 15px; LINE-HEIGHT: 30px; PADDING-LEFT: 15px; WIDTH: 350px; PADDING-RIGHT: 15px; BACKGROUND: #fafafa; BORDER-TOP: #ccc 2px solid; BORDER-RIGHT: #ccc 2px solid; PADDING-TOP: 15px\">认证码：<B style=\"COLOR: #66cc33\">#####</B><BR>（认证码在身份验证过程中需要用到，请妥善保管）</DIV><BR><BR>再次感谢您对wozuji.com的支持。 <BR><BR><BR>wozuji.com管理员 <BR></DIV>";
                content = content.Replace("*****", email);
                content = content.Replace("#####", code);

                SendMail sm = new SendMail();

                sm.sendmail(email, content, "我足迹团队联盟密码找回");
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }




        }

        #endregion

        #region 判断Email是否存在
        public  bool mailExist(String Email)
        {
            Wozuji.BLL.Member_t mb = new Wozuji.BLL.Member_t();
            return mb.MailExists(Email);
        }
        #endregion

        #region 用户名合法性检测
        public  bool NameLogic(string friendName)
        {
            if (friendName.Length < 3 || friendName.Length > 16)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion

        #region 检查email是否合法
        /// <summary>
        /// 检查email是否合法
        /// </summary>
        /// <param name="email">需要检查的email</param>
        /// <returns>合法true，不合法false</returns>
        public  bool isEmailLogic(string email)
        {

            Regex reg = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");

            if (!reg.IsMatch(email))
            {
                return false;
            }
            else
            {
                return true;
            }


        }
        #endregion

        #region 判断昵称是否存在
        public  bool NameExist(string Name)
        {
            Wozuji.BLL.Member_t mbdal = new Wozuji.BLL.Member_t();

            if (mbdal.NameExists(Name))
            {
                return true;
            }
            else
            {
                return false;
            }

        }
        #endregion

        #region 添加用户
        public  int adusers(string email, string friendname, string password, string username)
        {
            //判断用户是否存在
            if (mailExist(email))
            {
                return -1;

            }
            else
            {

                try
                {
                    Wozuji.Model.Member_t mb = new Wozuji.Model.Member_t();
                    Wozuji.BLL.Member_t mbdal = new Wozuji.BLL.Member_t();
                    mb.Member_Email = email;
                    mb.Member_Name = username;
                    mb.Member_FriendName = friendname;
                    mb.Member_Roleid = 1;
                    mb.Member_Sex = "0";
                    mb.Member_sign = "";
                    mb.Member_Status = 0;
                    mb.Member_Workfor = "";
                    mb.Member_Qq = "";
                    mb.Member_Msn = "";
                    mb.Member_Money = 10;
                    mb.Member_LoginTime = DateTime.Now;
                    mb.Member_isonline = "0";
                    mb.Member_Index = "";
                    mb.Member_Face = "default.png";
                    mb.Member_birthday = Convert.ToDateTime("1900-01-01");
                    mb.Member_ComeFrom = "000000000000";
                    mb.Member_location = 0;
                    mb.Member_Password = Wozuji.Common.Util.StringUtil.EncryptPassword(password, Wozuji.Common.Util.StringUtil.PasswordType.MD5.ToString());
                    mb.Member_private = "0";
                    mb.Member_occupation = "0";
                    mb.Member_ActiveValue = 0;
                    mb.Member_AutoLoginSerial = "false";
                    return mbdal.Add(mb);

                }
                catch (Exception ex)
                {
                    return 0;
                }
            }
        }
        #endregion

        #region 初始化用户信息
        public  string initUserData()
        {
            Wozuji.Model.Member_t member = new Wozuji.Model.Member_t();
            Wozuji.DAL.Member_t mbdal = new Wozuji.DAL.Member_t();
            Wozuji.Model_Web.onlineMemberInfo oml = new Model_Web.onlineMemberInfo();
            member = mbdal.GetModel_ByMemberId(Convert.ToInt32(HttpContext.Current.Session["userid"]));
            oml.Member_id = member.Member_Id;
            oml.Member_email = member.Member_Email;
            oml.Member_face = member.Member_Face;
            oml.Member_friendname = member.Member_FriendName;
            oml.Member_logintime = member.Member_LoginTime;
            oml.Member_money = member.Member_Money;
            oml.Member_name = member.Member_Name;
            oml.Member_sex = member.Member_Sex;
            oml.Member_sign = member.Member_sign;

            return JsonConvert.SerializeObject(oml);
        }
        #endregion

        #region  得到登录用户信息
        public  Wozuji.Model_Web.onlineMemberInfo getOmi()
        {
            Wozuji.Model.Member_t member = new Wozuji.Model.Member_t();
            Wozuji.DAL.Member_t mbdal = new Wozuji.DAL.Member_t();
            Wozuji.Model_Web.onlineMemberInfo oml = new Model_Web.onlineMemberInfo();
            member = mbdal.GetModel_ByMemberId(Convert.ToInt32(HttpContext.Current.Session["userid"]));
            oml.Member_id = member.Member_Id;
            oml.Member_email = member.Member_Email;
            oml.Member_face = member.Member_Face;
            oml.Member_friendname = member.Member_FriendName;
            oml.Member_logintime = member.Member_LoginTime;
            oml.Member_money = member.Member_Money;
            oml.Member_name = member.Member_Name;
            oml.Member_sex = member.Member_Sex;
            oml.Member_sign = member.Member_sign;
            return oml;

        }
        #endregion

        #region 得到用户加入的组群
        public   System.Data.DataSet getMemberTeam()
        {
            Wozuji.Model.Team_t team = new Wozuji.Model.Team_t();
            Wozuji.DAL.Team_t teamdal = new Wozuji.DAL.Team_t();
            return teamdal.GetList("Team_id in(select inteam_id from inteam_t where inteam_userid=" + HttpContext.Current.Session["userid"] + ") order by team_source");

        }
        #endregion

        #region 设置用户签名状态
        public  bool setMemberSign(string sign)
        {
            try
            {
                Wozuji.Model.Member_t member = new Wozuji.Model.Member_t();
                Wozuji.DAL.Member_t mbdal = new Wozuji.DAL.Member_t();
                member = mbdal.GetModel_ByMemberId(Convert.ToInt32(HttpContext.Current.Session["userid"]));
                member.Member_sign = sign;
                mbdal.Update(member);
                //写入membersign流水
                //Wozuji.Model
                Wozuji.Model.Member_sign_t ms = new Model.Member_sign_t();
                ms.member_sign = sign;
                ms.member_id = Convert.ToInt32(HttpContext.Current.Session["userid"]);
                new Wozuji.DAL.Member_sign_t().Add(ms);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }

        }
        #endregion


    }
}
